#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from PySide import QtGui, QtCore
import subprocess
import time

class TaskThread(QtCore.QThread):
    task_data = []
    substate = False
    status = False
    kill = False
    def __init__(self,item_model, parent=None):
        super(TaskThread, self).__init__(parent=parent)
        self.mutex = QtCore.QMutex()
        self.item_model = item_model
        
    def run(self):
        with QtCore.QMutexLocker(self.mutex):
            self.status = True
        while True:
            if self.task_data:
                cmd = self.task_data[0].get('cmd')
                item = self.task_data[0].get('item')
                itemModel = self.task_data[0].get('itemModel')
                try:
                    row = itemModel.indexFromItem(item).row()
                except:
                    self.task_data.remove(self.task_data[0])
                    continue
                else:
                    if row == -1:
                        self.task_data.remove(self.task_data[0])
                        continue

                manager = self.task_data[0].get('manager')
                file_name = self.task_data[0].get('file')
                task_state = 'doing'
                image = ":icons/stop_icon.png"
                # itemModel.setItem(row, 0, QtGui.QStandardItem(QtGui.QIcon(image), file_name))
                itemModel.item(row, 0).setText(file_name)
                itemModel.item(row, 0).setIcon(QtGui.QIcon(image))
                # itemModel.setItem(row, 4, QtGui.QStandardItem(task_state))
                itemModel.item(row, 4).setText(task_state)
                # 
                # task_state = 'Ok'
                # """
                if self.do_job(cmd):
                    task_state = 'Error'
                else:
                    task_state = 'Ok'
                # """
                #
                #self.emit(QtCore.SIGNAL("updateinfo"), "hello")
                if manager.taskOkData and file_name in manager.taskOkData:
                    image = ":icons/success.png"
                elif manager.taskErrorData and file_name in manager.taskErrorData:
                    image = ":icons/failure.png"
                else:
                    image = ":icons/failure.png"
                    
                #item = self.task_data[0].get('item')
                #itemModel = self.task_data[0].get('itemModel')
                
                try:
                    row = itemModel.indexFromItem(item).row()
                except:
                    continue
                else:
                    if row == -1:
                        continue
                # itemModel.setItem(row, 0, QtGui.QStandardItem(QtGui.QIcon(image), file_name))
                # itemModel.setItem(row, 4, QtGui.QStandardItem(task_state))
                itemModel.item(row, 0).setText(file_name)
                itemModel.item(row, 0).setIcon(QtGui.QIcon(image))
                itemModel.item(row, 4).setText(task_state)
                
                self.task_data.remove(self.task_data[0])
                #self.substate = False
 
    def subprocess_popen(self, *args, **kwargs):
        start_info = subprocess.STARTUPINFO()
        start_info.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
        start_info.wShowWindow = subprocess.SW_HIDE
        kwargs['startupinfo'] = start_info
        retcode = subprocess.Popen(*args, **kwargs)
        return retcode
        
    def do_job(self, cmd):
        print '>'*100
        print cmd
        p = self.subprocess_popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
        try:
            curline = p.stdout.readline()
            while(curline !=''):
                if self.kill:
                    time.sleep(2)
                    self.kill = False
                    if p.stdin:
                        p.stdin.close()
                    if p.stdout:
                        p.stdout.close()
                    if p.stderr:
                        p.stderr.close()
                    
                    try:
                        p.kill()
                    except:pass
                    
                    return
                curline = p.stdout.readline()
                print curline
                #self.emit(QtCore.SIGNAL("updateinfo"), curline)
                
                #if self.substate:
                #    if p.stdin:
                #        p.stdin.close()
                #    if p.stdout:
                #        p.stdout.close()
                #    if p.stderr:
                #        p.stderr.close()
                #    try:
                #        p.kill()
                #    except:pass
                #    return
        except Exception, e:
            print str(e)
            return
        p.wait()
        if p.stdin:
            p.stdin.close()
        if p.stdout:
            p.stdout.close()
        if p.stderr:
            p.stderr.close()
        try:
            p.kill()
        except:pass